import { INestApplication } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { SWAGGER_CONFIG } from './swagger.constants';

/**
 * 配置Swagger文档
 * @param app NestJS应用实例
 * @param configService 配置服务
 */
export function setupSwagger(
  app: INestApplication,
  configService?: ConfigService,
): void {
  const config = new DocumentBuilder()
    .setTitle(SWAGGER_CONFIG.title)
    .setDescription(SWAGGER_CONFIG.description)
    .setVersion(SWAGGER_CONFIG.version)
    .addBearerAuth()
    .setContact(
      SWAGGER_CONFIG.contact.name,
      SWAGGER_CONFIG.contact.url,
      SWAGGER_CONFIG.contact.email,
    )
    .setLicense(SWAGGER_CONFIG.license.name, SWAGGER_CONFIG.license.url)
    .setTermsOfService(SWAGGER_CONFIG.termsOfService)
    .setExternalDoc(
      SWAGGER_CONFIG.externalDocs.description,
      SWAGGER_CONFIG.externalDocs.url,
    );

  // 添加所有标签
  SWAGGER_CONFIG.tags.forEach((tag) => {
    config.addTag(tag.name, tag.description);
  });

  const builtConfig = config.build();

  const document = SwaggerModule.createDocument(app, builtConfig);

  // 可以从配置服务获取Swagger路径，如果没有提供配置服务，则使用默认路径
  const swaggerPath = configService?.get('swagger.path') || SWAGGER_CONFIG.path;

  SwaggerModule.setup(swaggerPath, app, document, {
    swaggerOptions: {
      persistAuthorization: true,
    },
  });

  // 如果提供了配置服务，可以获取应用端口，用于日志输出
  if (configService) {
    const port = configService.get('app.port') || 3000;
    console.log(
      `Swagger documentation is available at: http://localhost:${port}/${swaggerPath}`,
    );
  }
}
